package cn.wsalix.biz.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.admin.BaseUser;
import cn.anlaser.form.UploadFileForm;
import cn.anlaser.service.impl.CommonServiceImpl;
import cn.anlaser.status.FlagEnum;
import cn.anlaser.type.FileTypeEnum;
import cn.anlaser.type.ImageTypeEnum;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.biz.entity.Advertise;
import cn.wsalix.biz.entity.Article;
import cn.wsalix.biz.entity.Category;
import cn.wsalix.biz.entity.RelationAd;
import cn.wsalix.biz.entity.RelationCat;
import cn.wsalix.biz.form.AdvertiseForm;
import cn.wsalix.biz.form.ArticleForm;
import cn.wsalix.biz.repository.AdvertiseRepository;
import cn.wsalix.biz.repository.RelationAdRepository;
import cn.wsalix.biz.repository.RelationCatRepository;
import cn.wsalix.biz.service.AdvertiseService;
import cn.wsalix.biz.service.CategoryService;
import cn.wsalix.biz.type.AdTypeEnum;
import cn.wsalix.biz.type.CatTypeEnum;
import cn.wsalix.observable.service.ArtChangeService;
import cn.wsalix.observable.service.FileUploadService;
import cn.wsalix.shop.entity.Shop;

@Service("advertiseService")
public class AdvertiseServiceImpl extends
		CommonServiceImpl<AdvertiseForm, AdvertiseRepository, Advertise>
		implements AdvertiseService {
	@Autowired
	private AdvertiseRepository advertiseRepository;
	@Autowired
	private RelationCatRepository relationCatRepository;
	@Autowired
	private RelationAdRepository relationAdRepository;
	@Autowired
	private CategoryService categoryService;

	@Override
	public String module() {
		return "/biz/ad";
	}

	@Transactional
	@Override
	public Advertise getNew(AdvertiseForm form) {
		BaseUser user = userUtils.getUser();
		AdvertiseForm queryForm = new AdvertiseForm();
		queryForm.setFlag(FlagEnum.create);
		queryForm.setCreatedBy(user.getId());
		List<Advertise> resLst = findByForm(queryForm);
		if (!resLst.isEmpty()) {
			return resLst.get(0);
		} else {
			Advertise entity = new Advertise();
			traversalAssign(form, entity);
			entity.setFlag(FlagEnum.create);
			entity.setCreatedBy(user.getId());
			entity = add(entity);
			if (form.getShopId() != null) {
				RelationAd relationAd = new RelationAd();
				relationAd.setAdvertise(entity);
				relationAd.setAdType(AdTypeEnum.shop);
				relationAd.setFkId(form.getShopId());
				relationAdRepository.save(relationAd);
			}
			return entity;
		}
	}

	@Override
	public AdvertiseRepository getRepository() {
		return advertiseRepository;
	}

	@Override
	public Class<Advertise> getEntityClazz() {
		return Advertise.class;
	}

	@Transactional
	@Override
	public Advertise add(AdvertiseForm form) {
		if (form.getCatId() != null) {
			Category category = categoryService.findById(form.getCatId());
			form.setCategory(category);
		}

		Advertise obj = advertiseRepository.findOne(form.getId());
		traversalAssign(form, obj);
		obj.setFlag(FlagEnum.valid);
		return add(obj);
	}

	@Transactional
	@Override
	public Advertise edit(AdvertiseForm form) {
		if (form.getCatId() != null) {
			Category category = categoryService.findById(form.getCatId());
			form.setCategory(category);
		}

		return super.edit(form);
	}

	@Transactional
	@Override
	public void delete(Long id) {
		relationAdRepository.deleteByAdId(id);
		super.delete(id);
	}

	@Override
	public Map<String, SearchFilter> buildByForm(AdvertiseForm form) {
		Map<String, SearchFilter> filters = buildFilter(form);

		if (form.getCatId() != null && form.getCatId() != 0) {
			filters.put("category.id", new SearchFilter("category.id",
					Operator.EQ, form.getCatId()));
		}

		return filters;
	}

	@Transactional
	@Override
	public void update(Observable o, Object arg) {
		if (o instanceof FileUploadService) {
			FileUploadService fileUploadService = (FileUploadService) o;
			if (arg instanceof UploadFileForm) {
				UploadFileForm obj = (UploadFileForm) arg;
				if (obj.getType().ordinal() == FileTypeEnum.image.ordinal()) {
					if (obj.getImageType().equals(ImageTypeEnum.ad.name())) {
						if (obj.getFkId() != null && obj.getFkId() != 0) {
							if (obj.getCode() != null
									&& obj.getCode().equals("logo")) {
								Advertise ad = advertiseRepository.findOne(obj
										.getFkId());
								ad.setLogo(obj.getHttpUrl());
								super.edit(ad);
								/*
								 * // add Advertise ad = new Advertise();
								 * ad.setName(obj.getName());
								 * ad.setLogo(obj.getHttpUrl()); super.add(ad);
								 * // fileUploadService.setObj(ad); } else { //
								 * edit Advertise ad =
								 * advertiseRepository.findOne(obj .getFkId());
								 * ad.setLogo(obj.getHttpUrl()); super.edit(ad);
								 * // fileUploadService.setObj(ad);
								 */}
						}
					}
				}
			}
		}
		if (o instanceof ArtChangeService) {
			ArtChangeService artChangeService = (ArtChangeService) o;
			if (arg instanceof ArticleForm) {
				ArticleForm form = (ArticleForm) arg;
				Article article = artChangeService.getArticle();
				/*
				 * if (form.getType().ordinal() == ArticleEnum.ad.ordinal()) {
				 * if (form.getId() == null || form.getId() == 0) {// 文章新增
				 * AdArticle adArticle = new AdArticle();
				 * adArticle.setAd(advertiseRepository.findOne(form
				 * .getFkId())); adArticle.setArticle(article);
				 * adArticleRepository.save(adArticle); } else {// 文章修改 //
				 * article = edit(form); } }
				 */
			}
		}
	}

	@Override
	public Advertise findByCode(String code) {
		return advertiseRepository.findByCodeOne(code);
	}

	@Override
	public List<Advertise> findsByCode(String code) {
		return advertiseRepository.findsByCode(code);
	}

	@Transactional
	@Override
	public void addCat(Long adId, Category category) {
		RelationCat relationCat = new RelationCat();
		relationCat.setCategory(category);
		relationCat.setFkId(adId);
		relationCat.setCatType(CatTypeEnum.ad);
		relationCatRepository.save(relationCat);
	}

	@Transactional
	@Override
	public void delCat(Long adId, Long catId) {
		relationCatRepository.deleteByCatTypeAndFkid(adId, catId,
				CatTypeEnum.ad);
	}

	@Override
	public List<Advertise> findByUnShopId(Long shopId, Long userId) {
		List<Advertise> resultLst = relationAdRepository.findByTypeAndFkid(
				shopId, AdTypeEnum.shop);
		AdvertiseForm form = new AdvertiseForm();
		form.setFlag(FlagEnum.valid);
		form.setCreatedBy(userId);
		List<Advertise> srcLst = findByForm(form);
		List<Advertise> resLst = new ArrayList<Advertise>();
		for (Advertise obj : srcLst) {
			if (resultLst.contains(obj)) {
				obj.setSelect(true);
			}
			resLst.add(obj);
		}
		return resLst;
	}

}
